// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.designer.ui.process.models;

import java.util.ArrayList;
import java.util.List;

import org.dengues.core.components.EMFConnection;
import org.dengues.core.components.ENodeParameterName;
import org.dengues.core.components.IXMLComponent;
import org.dengues.core.components.NodePropertyParameter;
import org.dengues.core.metadata.MetadataTable;
import org.dengues.core.process.CompElement;
import org.dengues.core.process.CompProcessHelper;
import org.dengues.core.process.EConnectionType;
import org.dengues.core.process.ICompConnection;
import org.dengues.core.process.ICompNode;
import org.dengues.core.process.ICompProcess;
import org.dengues.designer.ui.i18n.Messages;
import org.dengues.designer.ui.process.editors.GEFComponentsEditor;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;

/**
 * qzhang class global comment. Detailled comment <br/>
 */
public class CompNode extends CompElement implements ICompNode {

    private final List<ICompConnection> incomingConnections;

    private final List<ICompConnection> outgoingConnections;

    private final IXMLComponent component;

    private ICompProcess compProcess;

    private static final long serialVersionUID = 1113123334234235L;

    public static final String PROP_NODE_LOCATION = "CompNode_location"; //$NON-NLS-1$

    private Point location = new Point();

    private String uniqueName;

    private CompNodeLabel nodeLabel;

    public static final String PROP_INCOMINGS = "incomingConnections"; //$NON-NLS-1$

    public static final String PROP_OUTGOINGS = "outgoingConnections"; //$NON-NLS-1$

    private List<EMFConnection> emfConnections;

    private CompNodeStatus nodeStatus;

    /**
     * qzhang CompNode constructor comment.
     */
    public CompNode(IXMLComponent component) {
        this.component = component;
        incomingConnections = new ArrayList<ICompConnection>();
        outgoingConnections = new ArrayList<ICompConnection>();
        init(component);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "init".
     * 
     * @param component2
     */
    private void init(IXMLComponent component2) {
        setElementParameters(component.createNodeParameters(this));
        nodeLabel = new CompNodeLabel(getUniqueName(), this);
        nodeStatus = new CompNodeStatus(this);
        emfConnections = component.createConnections();
    }

    public boolean isOutput(String name) {
        for (EMFConnection con : emfConnections) {
            if (con.getName().equals(name)) {
                return con.getMaxoutput() > getOutgoingConnections().size();
            }
        }
        return false;
    }

    public boolean isInput(String name) {
        for (EMFConnection con : emfConnections) {
            if (con.getName().equals(name)) {
                return con.getMaxinput() > getIncomingConnections().size();
            }
        }
        return false;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.designer.ui.gef.nodes.Element#getElementName()
     */
    @Override
    public String getCompName() {
        return component.getName();
    }

    /**
     * Getter for compProcess.
     * 
     * @return the compProcess
     */
    @Override
    public ICompProcess getCompProcess() {
        return this.compProcess;
    }

    /**
     * Sets the compProcess.
     * 
     * @param compProcess the compProcess to set
     */
    public void setCompProcess(ICompProcess compProcess) {
        this.compProcess = compProcess;
    }

    /**
     * Getter for component.
     * 
     * @return the component
     */
    public IXMLComponent getComponent() {
        return this.component;
    }

    /**
     * Getter for location.
     * 
     * @return the location
     */
    @Override
    public Point getLocation() {
        return this.location;
    }

    /**
     * Sets the location.
     * 
     * @param location the location to set
     */
    public void setLocation(Point location) {
        this.location = location;
        nodeLabel.setLocation(location);
        nodeStatus.setLocation((new Rectangle(getLocation(), getSize())).getTopRight());
        List<ICompConnection> conns = getOutgoingConnections();
        for (ICompConnection compConnection : conns) {
            CompConnection compConnection2 = ((CompConnection) compConnection);
            compConnection2.getConnectionLabel().changeLocation();
            if (compConnection2.getConnectionTrac() != null) {
                compConnection2.getConnectionTrac().changeLocation();
            }
        }
        conns = getIncomingConnections();
        for (ICompConnection compConnection : conns) {
            CompConnection compConnection2 = ((CompConnection) compConnection);
            compConnection2.getConnectionLabel().changeLocation();
            if (compConnection2.getConnectionTrac() != null) {
                compConnection2.getConnectionTrac().changeLocation();
            }
        }

        fireStructureChange(PROP_NODE_LOCATION, this.location);
    }

    /**
     * Getter for uniqueName.
     * 
     * @return the uniqueName
     */
    public String getUniqueName() {
        NodePropertyParameter param = getElementParameter(ENodeParameterName.UNIQUE_NAME.getName());
        if (param != null) {
            uniqueName = (String) param.getValue();
        }
        return this.uniqueName;
    }

    /**
     * Getter for incomingConnections.
     * 
     * @return the incomingConnections
     */
    public List<ICompConnection> getIncomingConnections() {
        return this.incomingConnections;
    }

    /**
     * Sets the incomingConnections.
     * 
     * @param incomingConnections the incomingConnections to set
     */
    public void addIncomingConnections(ICompConnection incomingConnection) {
        incomingConnections.add(incomingConnection);
        fireStructureChange(PROP_INCOMINGS, incomingConnections);
    }

    public void removeIncomingConnections(ICompConnection incomingConnection) {
        incomingConnections.remove(incomingConnection);
        fireStructureChange(PROP_INCOMINGS, incomingConnections);
    }

    /**
     * Getter for outgoingConnections.
     * 
     * @return the outgoingConnections
     */
    public List<ICompConnection> getOutgoingConnections() {
        return this.outgoingConnections;
    }

    /**
     * Sets the outgoingConnections.
     * 
     * @param outgoingConnections the outgoingConnections to set
     */
    public void addOutgoingConnections(ICompConnection outgoingConnection) {
        this.outgoingConnections.add(outgoingConnection);
        fireStructureChange(PROP_OUTGOINGS, outgoingConnections);
    }

    public void removeOutgoingConnections(ICompConnection outgoingConnection) {
        this.outgoingConnections.remove(outgoingConnection);
        fireStructureChange(PROP_OUTGOINGS, outgoingConnections);
    }

    /**
     * Sets the uniqueName.
     * 
     * @param uniqueName the uniqueName to set
     */
    public void setUniqueName(String uniqueName) {
        if (uniqueName == null) {
            this.uniqueName = CompProcessHelper.generateNewCompNodeName(getCompProcess(), getCompName());
        } else {
            this.uniqueName = CompProcessHelper.generateNewCompNodeName(getCompProcess(), uniqueName);
        }
        NodePropertyParameter param = getElementParameter(ENodeParameterName.UNIQUE_NAME.getName());
        if (param != null) {
            param.setValue(this.uniqueName);
            nodeLabel.setNodeLabel(this.uniqueName);
        }
    }

    /**
     * Getter for nodeLabel.
     * 
     * @return the nodeLabel
     */
    public CompNodeLabel getNodeLabel() {
        return this.nodeLabel;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.process.ICompElement#getSize()
     */
    @Override
    public Dimension getSize() {
        return new Dimension(GEFComponentsEditor.GRID_SIZE, GEFComponentsEditor.GRID_SIZE);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.process.ICompNode#isStart()
     */
    public boolean isStart() {
        return component.isStart();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.process.ICompNode#isSubProcessStart()
     */
    public boolean isSubProcessStart() {
        return getIncomingConnections().size() == 0;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.designer.ui.process.models.CompElement#toString()
     */
    @Override
    public String toString() {
        String s = getUniqueName();
        s = s + " : inputs["; //$NON-NLS-1$
        for (ICompConnection conn : getIncomingConnections()) {
            s = s + conn.getName() + ","; //$NON-NLS-1$
        }
        s = s + "]; outputs["; //$NON-NLS-1$
        for (ICompConnection conn : getOutgoingConnections()) {
            s = s + conn.getName() + ","; //$NON-NLS-1$
        }
        s = s + "]"; //$NON-NLS-1$
        return s;
    }

    /**
     * Getter for nodeStatus.
     * 
     * @return the nodeStatus
     */
    public CompNodeStatus getNodeStatus() {
        return this.nodeStatus;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "checkNode".
     */
    public void checkNode() {
        if (getElementParameter("METADATA") != null) {//$NON-NLS-1$
            if (getMetadataList().size() == 0 || getMetadataList().get(0) == null) {
                nodeStatus.setMessage(Messages.getString("CompNode.status.metadata", getUniqueName())); //$NON-NLS-1$
                nodeStatus.setType(CompNodeStatus.STATUS_ERROR);
                return;
            } else if (getMetadataList().get(0).getColumns() == null || getMetadataList().get(0).getColumns().size() == 0) {
                nodeStatus.setMessage(Messages.getString("CompNode.status.metadata.Empty", getUniqueName())); //$NON-NLS-1$
                nodeStatus.setType(CompNodeStatus.STATUS_WARNING);
                return;
            }
        }
        if (isInput(EConnectionType.MAIN.toString())) {
            nodeStatus.setMessage(Messages.getString("CompNode.status.input", getUniqueName())); //$NON-NLS-1$
            nodeStatus.setType(CompNodeStatus.STATUS_INFO);
        } else if (isOutput(EConnectionType.MAIN.toString())) {
            nodeStatus.setMessage(Messages.getString("CompNode.status.output", getUniqueName())); //$NON-NLS-1$
            nodeStatus.setType(CompNodeStatus.STATUS_INFO);
        } else {
            nodeStatus.setType(CompNodeStatus.STATUS_NORMAL);
        }
    }

    @Override
    public CompNode clone() {
        CompNode newNode = null;
        try {
            newNode = new CompNode(getComponent());
            Point p = new Point();
            p.x = newNode.getLocation().x;
            p.y = newNode.getLocation().y;
            newNode.setLocation(p);
            List<NodePropertyParameter> ps = new ArrayList<NodePropertyParameter>();
            for (NodePropertyParameter param : getElementParameters()) {
                ps.add(param.clone());
            }
            newNode.setElementParameters(ps);
            List<MetadataTable> ts = new ArrayList<MetadataTable>();
            for (MetadataTable metadataTable : getMetadataList()) {
                ts.add(metadataTable.clone());
            }
            newNode.setMetadataList(ts);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newNode;
    }
}
